聊一聊 vue 中 ref、reactive 重置属性的优雅做法 您所在的位置:网站首页 vue 中怎么重置 data 聊一聊 vue 中 ref、reactive 重置属性的优雅做法

聊一聊 vue 中 ref、reactive 重置属性的优雅做法

#聊一聊 vue 中 ref、reactive 重置属性的优雅做法| 来源: 网络整理| 查看: 265

一直在找一个重置ref属性的方法,百度无果,翻开ref实现源码,发现RefImpl 这个类没有暴露,不方便继承,也不是很好去改,于是想到闭包做法,来实现属性重置的效果。

由于是二次包装方法,用的时候需要区别ref,和私有的$ref方法,有更好的方法欢迎下面留言。

import { cloneDeep } from 'lodash-es' import { ref, reactive } from 'vue' // 二次包装一层的 ref export function $ref(o) { const b = cloneDeep(o) const j = ref(o) j._reset = Object.assign.bind(null, j.value, b) return j } // 二次包装一层的 reactive export function $reactive(o) { const b = cloneDeep(o) const j = reactive(o) j._reset = Object.assign.bind(null, j, b) return j } ------------------------------------------------------------------------------- // main.js 直接挂载 proxy 上 app.config.globalProperties.$ref = $ref app.config.globalProperties.$reactive = $reactive ------------------------------------------------------------------------------- // 组件中使用时 const { proxy: { $ref, $reactive } } = getCurrentInstance() const pagination = $ref({ pageNum: 1, pageSize: 10, total: 0 }) const reset = () => { // 可以很方便直接调用重置函数来重置属性 pagination.value._reset() }


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有